package com.example.farmer.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.farmer.Adapter.ImageSelectionAdapter;
import com.example.farmer.Adapter.PostCircleAdapter;
import com.example.farmer.Presenter.CirclePostPresenter;
import com.example.farmer.R;
import com.example.farmer.View.Circle.CirclePostView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PostCircleActivity extends AppCompatActivity implements CirclePostView {
    private EditText editTextPostContent;
    private ImageButton buttonAddMedia;
    private Button buttonPostSend;

    private CirclePostPresenter mPresenter;
    private ArrayList<Uri> mImageUris = new ArrayList<>();
    private ImageSelectionAdapter imageSelectionAdapter;
    private RecyclerView recyclerViewImages;
    private Uri selectedImageUri;

    private static final int CAMERA_REQUEST_CODE = 100;
    private static final int GALLERY_REQUEST_CODE = 101;
    private SharedPreferences sharedPreferences; // 当前登录用户的手机号
    private PostCircleAdapter circleAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_post);

        editTextPostContent = findViewById(R.id.editText_post_content);
        buttonAddMedia = findViewById(R.id.button_add_media);
        buttonPostSend = findViewById(R.id.button_post_send);

        recyclerViewImages = findViewById(R.id.recyclerViewImages);
        recyclerViewImages.setLayoutManager(new LinearLayoutManager(this));
        imageSelectionAdapter = new ImageSelectionAdapter(mImageUris);
        recyclerViewImages.setAdapter(imageSelectionAdapter);

        mPresenter = new CirclePostPresenter(this);

        buttonAddMedia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMediaOptions();
            }
        });
        buttonPostSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences sharedPreferences = getSharedPreferences("loginNumber" , Context.MODE_PRIVATE);
                String userNumber = sharedPreferences.getString("userNumber", null);


                String content = editTextPostContent.getText().toString();
                if (!content.isEmpty()) {
                    if (mImageUris !=null && !mImageUris.isEmpty()){
                        // 发送帖子内容和图片Uri
                        mPresenter.post(content, selectedImageUri.toString(),userNumber);
                    }else {
                        mPresenter.post(content, null,userNumber);
                    }

                } else {
                    Toast.makeText(PostCircleActivity.this, "帖子内容不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    // 在PostCircleActivity中添加获取电话号码的方法
//    private String getLoggedInPhoneNumber() {
//        SharedPreferences sharedPreferences = getSharedPreferences("loginNumber", Context.MODE_PRIVATE);
//        return sharedPreferences.getString("userNumber", null); // 假设您的SharedPreferences的键是"userNumber"
//        // 隐藏手机号中间四位
//        String hiddenNumber = hideMiddleFourDigits(userNumber);
//        // 将隐藏后的手机号设置到TextView上
//        mPresenter.per_number.setText(hiddenNumber);
//    }

    @Override
    public void showPostSuccess() {
        Toast.makeText(this, "发布成功", Toast.LENGTH_SHORT).show();
        redirectToCircleActivity();
    }

    private void redirectToCircleActivity() {

        finish();// 结束当前活动并返回
    }

    @Override
    public void showPostError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }

//    @Override
//    public void showPosts(List<CirclePost> posts) {
//        // 这里实现如何展示帖子列表，例如使用RecyclerView的Adapter更新数据
//    }
    @Override
    public void showLoading() {
        // 显示加载指示器的逻辑
    }

    @Override
    public void hideLoading() {
        // 隐藏加载指示器的逻辑
    }

    @Override
    public Context getContext() {
        return this;
    }

    private void showMediaOptions() {
        CharSequence options[] = {"拍照", "从相册选择"};
        AlertDialog.Builder builder = new AlertDialog.Builder(PostCircleActivity.this);
        builder.setTitle("选择媒体");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) { // 拍照
                    openCamera();
                } else if (which == 1) { // 从相册选择
                    openGallery();
                }
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void openCamera() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    CAMERA_REQUEST_CODE);
        } else {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            } else {
                Toast.makeText(this, "没有可用的相机应用。", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openCamera();
            } else {
                Toast.makeText(this, "需要相机权限来拍照。", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, GALLERY_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CAMERA_REQUEST_CODE) {
                Bundle extras = data.getExtras();
                assert extras != null;
                Bitmap photo = extras.getParcelable("data");
                String imageUrl = saveImageToStorage(photo, this);
                addImageToSelection(photo);
                if (imageUrl != null) {
                    selectedImageUri = Uri.fromFile(new File(imageUrl));
                    imageSelectionAdapter.notifyItemInserted(mImageUris.size() - 1);
                }
            } else if (requestCode == GALLERY_REQUEST_CODE) {
                selectedImageUri = data.getData();
                String imageUrl = getImagePathFromUri(selectedImageUri);
                if (imageUrl != null) {
                    imageSelectionAdapter.notifyItemInserted(mImageUris.size() - 1);
                    addImageToSelection(selectedImageUri);
                }
            }
        }
        updateImageAdapter(mImageUris);

    }

    private String getImagePathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        try (Cursor cursor = getContentResolver().query(uri, projection, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                return cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String saveImageToStorage(Bitmap bitmapImage, Context context) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            byte[] bitmapData = bos.toByteArray();

            File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (storageDir != null) {
                File imageFile = createImageFile(storageDir);
                try (FileOutputStream fos = new FileOutputStream(imageFile)) {
                    fos.write(bitmapData);
                    return imageFile.getAbsolutePath();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private File createImageFile(File storageDir) {
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "POST_" + timeStamp + "_";
        int index = 0;
        File imageFile;
        do {
            imageFile = new File(storageDir, imageFileName + index + ".jpg");
            index++;
        } while (imageFile.exists());
        return imageFile;
    }

    private void addImageToSelection(Object selection) {
        if (selection instanceof Bitmap) {
            // 处理相机拍摄的 Bitmap
            Bitmap photo = (Bitmap) selection;
            // 将 Bitmap 转换为文件并保存，然后获取 Uri
            String photoFile = saveImageToStorage(photo, this);
            if (photoFile != null) {
                Uri photoUri = Uri.fromFile(new File(photoFile));
                mImageUris.add(photoUri);
                imageSelectionAdapter.notifyItemInserted(mImageUris.size() - 1);
            }
        } else if (selection instanceof Uri) {
            // 处理从相册选择的 Uri
            Uri imageUri = (Uri) selection;
            mImageUris.add(imageUri);
            imageSelectionAdapter.notifyItemInserted(mImageUris.size() - 1);
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private void updateImageAdapter(List<Uri> newUris) {
        if (imageSelectionAdapter == null) {
            imageSelectionAdapter = new ImageSelectionAdapter(newUris);
            recyclerViewImages.setAdapter(imageSelectionAdapter);
        } else {
            imageSelectionAdapter.mImageUris = newUris; // 更新图片列表
            imageSelectionAdapter.notifyDataSetChanged(); // 通知数据已改变
        }
    }
}


